package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.mall.dto.OrderCreateParam;
import com.pdd.mall.entity.Address;
import com.pdd.mall.entity.Order;
import com.pdd.mall.entity.OrderItem;
import com.pdd.mall.entity.Product;
import com.pdd.mall.entity.Promotion;
import com.pdd.mall.mapper.AddressMapper;
import com.pdd.mall.mapper.OrderItemMapper;
import com.pdd.mall.mapper.OrderMapper;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.service.OrderService;
import com.pdd.mall.service.PromotionService;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private PromotionService promotionService;

    @Override
    @Transactional
    public Order createOrder(OrderCreateParam param, Long userId) {
        // 1. 校验地址
        Address address = addressMapper.selectById(param.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            throw new IllegalArgumentException("收货地址不存在或不属于当前用户");
        }

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo());
        order.setStatus(0); // 待付款

        // 设置收货信息
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhone());
        order.setReceiverAddress(address.getProvince() + " " + address.getCity() + " " +
                address.getDistrict() + " " + address.getDetail());

        // 3. 计算订单金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalPromotionAmount = BigDecimal.ZERO;
        List<OrderItem> orderItems = new ArrayList<>();

        // 记录所有商品的促销活动ID，用于后续检查是否有满减活动
        Set<Long> promotionIds = new HashSet<>();

        // 第一次遍历：计算商品原价总额和收集促销活动ID
        for (OrderCreateParam.OrderItemParam itemParam : param.getItems()) {
            // 查询商品
            Product product = productMapper.selectById(itemParam.getProductId());
            if (product == null || product.getStatus() != 1) {
                throw new IllegalArgumentException("商品不存在或已下架");
            }

            // 检查库存
            if (product.getStock() < itemParam.getQuantity()) {
                throw new IllegalArgumentException("商品库存不足");
            }

            // 获取商品原价
            BigDecimal originalPrice = product.getPrice();

            // 累加订单总金额（原价总额）
            totalAmount = totalAmount.add(originalPrice.multiply(new BigDecimal(itemParam.getQuantity())));

            // 获取商品的促销信息
            Map<String, Object> promotionInfo = promotionService.getProductPromotion(product.getId());
            if ((Boolean) promotionInfo.get("hasPromotion")) {
                Promotion promotion = (Promotion) promotionInfo.get("promotion");
                promotionIds.add(promotion.getId());
            }
        }

        // 检查是否有满减活动，并计算满减折扣
        BigDecimal orderDiscount = BigDecimal.ZERO;
        for (Long promotionId : promotionIds) {
            Promotion promotion = promotionService.getPromotionDetail(promotionId, null);
            if (promotion != null && "discount".equals(promotion.getType())) {
                // 解析满减规则
                Map<String, Object> rules = parsePromotionRules(promotion.getRules());

                // 获取满减条件和折扣金额
                BigDecimal condition;
                if (rules.containsKey("condition")) {
                    condition = new BigDecimal(rules.get("condition").toString());
                } else if (rules.containsKey("threshold")) {
                    condition = new BigDecimal(rules.get("threshold").toString());
                } else {
                    continue; // 如果没有条件字段，跳过
                }

                BigDecimal discount = new BigDecimal(rules.get("discount").toString());

                // 如果订单总金额满足满减条件，应用折扣
                if (totalAmount.compareTo(condition) >= 0) {
                    orderDiscount = discount;
                    System.out.println("应用满减活动：满" + condition + "减" + discount);
                    System.out.println("订单总金额：" + totalAmount + "，满减条件：" + condition + "，满减金额：" + discount);
                    break; // 只应用一个满减活动
                } else {
                    System.out.println("订单总金额不满足满减条件：订单总金额=" + totalAmount + "，满减条件=" + condition);
                }
            }
        }

        // 第二次遍历：处理每个商品的促销价格和创建订单项
        for (OrderCreateParam.OrderItemParam itemParam : param.getItems()) {
            Product product = productMapper.selectById(itemParam.getProductId());
            BigDecimal originalPrice = product.getPrice();

            // 计算单个商品的促销价格（针对折扣和秒杀类型的促销）
            BigDecimal promotionPrice = promotionService.calculatePromotionPrice(product.getId(), originalPrice);

            // 计算商品级别的促销折扣金额
            BigDecimal itemDiscount = originalPrice.subtract(promotionPrice).multiply(new BigDecimal(itemParam.getQuantity()));

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductPrice(originalPrice); // 保存原价
            orderItem.setQuantity(itemParam.getQuantity());

            // 使用促销价格计算总价
            BigDecimal itemTotal = promotionPrice.multiply(new BigDecimal(itemParam.getQuantity()));
            orderItem.setTotalPrice(itemTotal);

            // 累加商品级别的促销折扣金额
            totalPromotionAmount = totalPromotionAmount.add(itemDiscount);

            // 减少商品库存
            product.setStock(product.getStock() - itemParam.getQuantity());
            productMapper.updateById(product);

            orderItems.add(orderItem);
        }

        // 添加订单级别的满减折扣
        totalPromotionAmount = totalPromotionAmount.add(orderDiscount);

        // 设置订单金额
        order.setTotalAmount(totalAmount);
        order.setPromotionAmount(totalPromotionAmount); // 设置促销折扣金额
        order.setPayAmount(totalAmount.subtract(totalPromotionAmount)); // 实付金额 = 总金额 - 促销折扣

        // 4. 保存订单
        orderMapper.insert(order);

        // 5. 保存订单项
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderNo(order.getOrderNo());
            orderItemMapper.insert(orderItem);
        }

        return order;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        // 生成格式：年月日时分秒+4位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String randomStr = String.format("%04d", randomNum);

        return dateStr + randomStr;
    }

    @Override
    public Page<Order> getOrderList(Long userId, Integer status, Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 按状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("create_time");

        return orderMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Order getOrderDetail(String orderNo, Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("user_id", userId);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    public List<OrderItem> getOrderItemList(Long orderId) {
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return orderItemMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public boolean cancelOrder(String orderNo, Long userId) {
        // 查询订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", 0); // 只有待付款的订单才能取消

        Order order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            return false; // 订单不存在或状态不正确
        }

        // 删除订单项
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id", order.getId());
        orderItemMapper.delete(orderItemQueryWrapper);

        // 删除订单
        int result = orderMapper.deleteById(order.getId());
        return result > 0;
    }

    @Override
    public boolean updateOrderStatus(String orderNo, Integer status) {
        // 查询订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);

        Order order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            return false; // 订单不存在
        }

        // 更新订单状态
        order.setStatus(status);

        // 根据状态设置相应的时间
        if (status == 1) { // 待发货
            order.setPayTime(LocalDateTime.now());
        } else if (status == 2) { // 待收货
            order.setDeliveryTime(LocalDateTime.now());
        } else if (status == 3) { // 已完成
            order.setReceiveTime(LocalDateTime.now());
        }

        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    public Page<Order> getMerchantOrderList(Long merchantId, Integer status, Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);

        // 由于订单表中没有merchant_id字段，我们需要通过订单项关联商品，再通过商品关联商家
        // 这里我们使用一个子查询来实现

        // 1. 先查询属于该商家的所有商品ID
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("merchant_id", merchantId);
        productQueryWrapper.select("id");
        List<Object> productIds = productMapper.selectObjs(productQueryWrapper);

        if (productIds.isEmpty()) {
            // 如果商家没有商品，直接返回空页
            return page;
        }

        // 2. 查询包含这些商品的订单项
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.in("product_id", productIds);
        orderItemQueryWrapper.select("DISTINCT order_id");
        List<Object> orderIds = orderItemMapper.selectObjs(orderItemQueryWrapper);

        if (orderIds.isEmpty()) {
            // 如果没有相关订单，直接返回空页
            return page;
        }

        // 3. 查询这些订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.in("id", orderIds);

        // 按状态筛选
        if (status != null) {
            orderQueryWrapper.eq("status", status);
        }

        orderQueryWrapper.orderByDesc("create_time");

        return orderMapper.selectPage(page, orderQueryWrapper);
    }

    @Override
    public Order getMerchantOrderDetail(String orderNo, Long merchantId) {
        // 1. 先查询订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no", orderNo);
        Order order = orderMapper.selectOne(orderQueryWrapper);

        if (order == null) {
            return null;
        }

        // 2. 查询订单项
        QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
        orderItemQueryWrapper.eq("order_id", order.getId());
        List<OrderItem> orderItems = orderItemMapper.selectList(orderItemQueryWrapper);

        // 3. 检查是否包含该商家的商品
        boolean containsMerchantProduct = false;
        for (OrderItem orderItem : orderItems) {
            Product product = productMapper.selectById(orderItem.getProductId());
            if (product != null && product.getMerchantId().equals(merchantId)) {
                containsMerchantProduct = true;
                break;
            }
        }

        // 如果订单不包含该商家的商品，返回null
        if (!containsMerchantProduct) {
            return null;
        }

        return order;
    }

    @Override
    @Transactional
    public boolean shipOrder(String orderNo, Long merchantId, String trackingNo) {
        // 1. 获取订单详情
        Order order = getMerchantOrderDetail(orderNo, merchantId);
        if (order == null || order.getStatus() != 1) { // 只有待发货的订单才能发货
            return false;
        }

        // 2. 更新订单状态为已发货
        order.setStatus(2); // 已发货
        order.setDeliveryTime(LocalDateTime.now());

        // 3. 设置物流单号（如果有）
        if (trackingNo != null && !trackingNo.isEmpty()) {
            order.setTrackingNo(trackingNo);
        }

        int result = orderMapper.updateById(order);
        return result > 0;
    }

    @Override
    public boolean updateMerchantOrderStatus(String orderNo, Long merchantId, Integer status) {
        // 1. 获取订单详情
        Order order = getMerchantOrderDetail(orderNo, merchantId);
        if (order == null) {
            return false;
        }

        // 2. 更新订单状态
        order.setStatus(status);

        // 3. 根据状态设置相应的时间
        if (status == 2) { // 已发货
            order.setDeliveryTime(LocalDateTime.now());
        } else if (status == 3) { // 已完成
            order.setReceiveTime(LocalDateTime.now());
        }

        int result = orderMapper.updateById(order);
        return result > 0;
    }

    /**
     * 解析促销规则JSON
     */
    private Map<String, Object> parsePromotionRules(String rulesJson) {
        Map<String, Object> rules = new HashMap<>();

        if (rulesJson == null || rulesJson.isEmpty()) {
            return rules;
        }

        // 简单解析，实际应该使用JSON库
        rulesJson = rulesJson.replace("{", "").replace("}", "").replace("\"", "");
        String[] pairs = rulesJson.split(",");

        for (String pair : pairs) {
            String[] keyValue = pair.split(":");
            if (keyValue.length == 2) {
                String key = keyValue[0].trim();
                String value = keyValue[1].trim();

                // 尝试转换为数字
                try {
                    if (value.contains(".")) {
                        rules.put(key, Double.parseDouble(value));
                    } else {
                        rules.put(key, Integer.parseInt(value));
                    }
                } catch (NumberFormatException e) {
                    rules.put(key, value);
                }
            }
        }

        return rules;
    }
}
